package com.mastercard.labs

import static org.junit.Assert.*
import org.junit.*

import com.opensymphony.module.sitemesh.html.Text;

class DealServiceTests {
	def dealService
	
    @Before
    void setUp() {
        // Setup logic here
//		dealService = new DealService()
    }

    @After
    void tearDown() {
        // Tear down logic here
    }

    @Test
    void testGetDeals() {
        def user = User.findByUsername("ZHONGDE")
		def avgSpending = dealService.getAverageSpending(user)
		def merchants = dealService.getFavoriteMerchants(user)
		def deals = dealService.getDeals(user)
		for (Deal deal in deals) {
			// 1 - Test deal price must be smaller than average spending
			assertTrue (deal.price < avgSpending)
			// 2 - Test deal must be inside the merchant that user have bought
			assertTrue (deal.merchant in merchants)
		}
    }
	
	@Test
	void testGetAverageSpending() {
		
	}
	
	@Test
	void testSearchDeals() {
		def user = User.findByUsername("ZHONGDE")
		ArrayList deals = dealService.searchDeals("AUDI")
		
		// Test deal size
		assertTrue (deals.size() == 1)
		
		
		// Test that the deal must contain the search text
		String text = "Promotion"
		deals = dealService.searchDeals(text)
		for (Deal deal in deals) {
			boolean test1 = deal.title.toLowerCase().contains(text.toLowerCase())
			boolean test2 = deal.description.toLowerCase().contains(text.toLowerCase())
			boolean test3 = deal.merchant.name.toLowerCase().contains(text.toLowerCase())
			boolean test4 = deal.tags.toLowerCase().contains(text.toLowerCase())
			assertTrue (test1 || test2 || test3 || test4)
		}
	}
	
	@Test
	void testSearchByCondition() {
		def searchTitle = 'Promotion'
		def	searchCountry = 1
		def	searchMerchant = 1
		def cat1 = Category.get(5)
		
		def	searchCategories = 5
//		def	searchDate = new Date()
		
		log.info 'deal search begin:'
		
		def dealInstanceList = dealService.searchByCondition(
			searchTitle,
			searchCountry,
			searchMerchant,
			searchCategories);
		
		for (Deal deal in dealInstanceList) {

			log.info '###deal:' + deal
			
			assertTrue (deal.title.indexOf(searchTitle) > -1)
				
			assertEquals(searchMerchant, deal.merchant.id)
			
			assertEquals(searchCountry, deal.country.id)
			
			assertTrue (cat1 in deal.categories)
			/*
			assertTrue ( !searchDate.before(deal.startDate))
			
			assertTrue ( !searchDate.after(deal.endDate))*/
		}
		log.info 'deal search end'
		
	}
	
	@Test
	void testSearchDealForDashboard() {
		def dealInstanceList = dealService.searchDealForDashboard()
		// Test the size of deal list must be less than 5
		log.info 'size of deal list:' + dealInstanceList.size()
		
		assertTrue (dealInstanceList.size <= 5)
		
		// Test the top 5 deal start date
		def startDate = dealInstanceList.getAt(dealInstanceList.size() -1).getStartDate()
		
		def result = Deal.createCriteria().list {
			gt("startDate", startDate)
		}
		
		assertTrue (result.size <= 5)
	}
	
	
}
